package com.wwc.sc.controller;

import com.wwc.sc.entities.Payment;
import com.wwc.sc.entities.result.CommonResult;
import com.wwc.sc.lb.LoadBalanced;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author WWC
 */
@RestController
@Slf4j
@RequestMapping(value = "/consumer/payment")
public class OrderController {
    /**
     * 单机版配置，可以写死地址
     */
    //public static final String PAYMENT_URL = "http://localhost:8001/";

    /**
     *集群版是根据服务名来调用服务提供者的，必须提供负载均衡算法，否则不知道该调那个服务
     */
    public static final String PAYMENT_URL = "http://SPRING-CLOUD-PROVIDER-EUREKA-PAYMENT";


    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalanced loadBalanced;

    @RequestMapping(value = "/create")
    public CommonResult create(Payment payment) {
        CommonResult result = restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        return result;
    }

    @RequestMapping(value = "/getPaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        CommonResult result = restTemplate.getForObject(PAYMENT_URL + "/payment/getPaymentById/" + id, CommonResult.class);
        return result;
    }

    @GetMapping("/loadBalanced")
    public String getPaymentLoadBalanced() {

        List<ServiceInstance> instances = discoveryClient.getInstances("SPRING-CLOUD-PROVIDER-EUREKA-PAYMENT");

        if(instances == null || instances.size()<=0) {
            return null;
        }

        ServiceInstance serviceInstance = loadBalanced.instance(instances);
        URI uri = serviceInstance.getUri();

        return restTemplate.getForObject(uri+"/payment/loadBalanced",String.class);
    }

    @GetMapping("/zipkin")
    public String paymentZipkin() {
        String result = restTemplate.getForObject("http://localhost:8001"+"/payment/zipkin", String.class);
        return result;
    }

}
